<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <div>
      <!-- 卡片视图区域 -->
      <el-card class="box-card">
        <!-- 搜索与添加区域 -->
        <!-- Layout布局 - > 混合布局
           :gutter="20" 两个格子之间的间隔
        -->

        <!-- 搜索栏 -->
        <el-row :gutter="24" style="align-items: center;display: flex;">
          <el-col :span="3">
            <QueryOptions title="状态">
              <template>
                <el-dropdown @command="handleStatus" size="small">
                  <span class="el-dropdown-link">
                    {{ queryBody.status ? (queryBody.status == 1 ? "正常" : "冻结") : "下拉菜单" }}<i
                      class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="1">正常</el-dropdown-item>
                    <el-dropdown-item command="2">冻结</el-dropdown-item>
                    <el-dropdown-item command="">ALL</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </QueryOptions>
          </el-col>
          <el-col :span="4">
            <QueryOptions title="所在部门">
              <el-popover placement="bottom" trigger="click">
                <el-tree style=" float: left;" :data="deptTree" :props="deptProps" accordion
                  @node-click="handleNodeClick">
                </el-tree>
                <el-button slot="reference" style="border: none;width: 100%;" size="small">{{ deptName }}<i
                    class="el-icon-arrow-down el-icon--right"></i></el-button>
              </el-popover>

            </QueryOptions>
          </el-col>
          <el-col :span="5">
            <QueryOptions title="用户名"><el-input placeholder="请输入用户名" v-model="queryBody.username" size="small"
                class="my-input"></el-input>
            </QueryOptions>
          </el-col>
          <el-col :span="5">
            <QueryOptions title="用户昵称"><el-input placeholder="请输入用户昵称" v-model="queryBody.nickname" size="small"
                class="my-input"></el-input>
            </QueryOptions>
          </el-col>
          <el-col :span="1">
            <el-button @click="search" icon="el-icon-search" style="color:#fff;background-color: #007d71;"></el-button>
          </el-col>
        </el-row>

        <div style="margin: 1rem 0;display: flex;justify-content: space-between;">
          <div>
            <!-- 重置密码 -->
            <el-button type="primary" @click="rest_pwd" icon="el-icon-edit" style="background:rgb(0, 125, 113);">
              重置密码
            </el-button>
            <!-- 角色分配 -->
            <el-button type="primary" @click="edit_role" icon="el-icon-s-custom" style="background:rgb(0, 125, 113); ">
              角色分配
            </el-button>
          </div>

          <div>
            <!-- 添加用户 -->
            <el-button type="primary" @click="addUser" icon="el-icon-edit" style="background:rgb(0, 125, 113);">
              添加
            </el-button>
            <!-- 操作 -->
            <!-- <el-select type="primary" @click="operate" icon="el-icon-s-custom" v-model="operation" popper-class="dropdown"
              style=" margin-left: 0.5rem; width: 5rem;" placeholder="操作">
              <el-option v-for="item in operates" :key="item.value" :label="item.label" :value="item.value">
              </el-option> 
            </el-select>-->
          </div>
        </div>
        <!-- 添加用户 -->
        <!-- <el-col :span="4">
            <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
          </el-col> -->

        <!-- 系统用户列表区域
      用户名 用户昵称  所在部门  性别  电话  邮箱  创建时间  状态  操作
       -->
        <el-table :data="userList" ref="multipleTable" border style="width: 100%" key="id"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column type="index" :align="align"></el-table-column>
          <el-table-column prop="username" label="用户名" width="150" :align="align"></el-table-column>
          <el-table-column prop="nickname" label="用户昵称" width="150" :align="align"></el-table-column>
          <el-table-column prop="deptName" label="所在部门" :align="align"></el-table-column>
          <el-table-column prop="sex" label="性别" :align="align">
            <template slot-scope="scope">
              <el-tag :type="scope.row.sex == 1 ? 'primary' : 'danger'" disable-transitions>{{ scope.row.sex == 1 ? '男'
                : '女' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱" :align="align"> </el-table-column>
          <el-table-column prop="createDate" label="创建时间" :align="align"> </el-table-column>
          <el-table-column prop="status" label="状态" :align="align">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : (scope.row.status == 2 ? 'primary' : 'danger')"
                disable-transitions>
                {{ scope.row.status === 1 ? "正常" : (scope.row.status === 2 ? "冻结" : "删除") }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="op" label="操作" width="200px">
            <template slot-scope="scope">
              <el-button @click="activeUser(scope.row)" type="success" size="mini" v-show="scope.row.status != 1"
                plain>激活</el-button>
              <el-button @click="freezeUser(scope.row)" type="primary" size="mini" v-show="scope.row.status != 2"
                style="margin-left: 0;" plain>冻结</el-button>
              <el-button @click="deleteUser(scope.row)" type="danger" size="mini" v-show="scope.row.status != 3"
                style="margin-left: 0;" plain>删除</el-button>
              <el-button @click="updateUser(scope.row)"
                style="color: #fff;background-color:rgba(0, 125, 113,.5);border:1px solid #007d71;margin-left: 0;"
                size="mini" plain>修改</el-button>
            </template>

          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="1"
          :page-sizes="[5, 10, 15, 20]" :page-size="queryBody.pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="userTotal">
        </el-pagination>
      </el-card>

      <!-- 添加用户的对话框 -->
      <el-dialog title="添加用户" :visible.sync="dialogVisible" @close="addDialogClose" width="40%">
        <!-- 内容主题区域 -->
        <el-form :model="userForm" :rules="userFormRules" ref="addFormRef" label-width="100px">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="userForm.username"></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="userForm.nickname"></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input type="password" autocomplete="off" v-model="userForm.password"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPass">
            <el-input type="password" autocomplete="off" v-model="userForm.checkPass"></el-input>
          </el-form-item>
          <el-form-item label="所在部门" prop="deptId">
            <el-popover placement="bottom-start" width="400" trigger="click">
              <el-tree :data="deptTree" :props="deptProps" accordion @node-click="handleNodeUserDept">
              </el-tree>
              <el-button slot="reference" icon="el-icon-arrow-down">{{ userForm.deptName }} </el-button>
            </el-popover>
          </el-form-item>
          <el-form-item label="邮箱地址" prop="email">
            <el-input v-model="userForm.email"></el-input>
          </el-form-item>
          <el-form-item label="选择性别">
            <el-radio-group v-model="userForm.sex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="userForm.remark"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogClose">取 消</el-button>
          <el-button type="primary" @click="submitAddUser">确 定</el-button>
        </span>
      </el-dialog>


      <!-- 修改用户的对话框 -->
      <el-dialog title="修改用户" :visible.sync="dialogUpdateVisible" @close="updateDialogClose" width="40%">
        <!-- 内容主题区域 -->
        <el-form :model="userForm" :rules="userFormRules" ref="updateFormRef" label-width="100px">
          <el-form-item label="用户ID" prop="id">
            <el-input :value="userForm.id" disabled></el-input>
          </el-form-item>
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="userForm.username"></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="userForm.nickname"></el-input>
          </el-form-item>
          <el-form-item label="所在部门" prop="deptId">
            <el-popover placement="bottom-start" width="400" trigger="click">
              <el-tree :data="deptTree" :props="deptProps" accordion @node-click="handleNodeUserDept">
              </el-tree>
              <el-button slot="reference" icon="el-icon-arrow-down">{{ userForm.deptName }} </el-button>
            </el-popover>
          </el-form-item>
          <el-form-item label="邮箱地址" prop="email">
            <el-input v-model="userForm.email"></el-input>
          </el-form-item>
          <el-form-item label="选择性别">
            <el-radio-group v-model="userForm.sex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="userForm.remark"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="updateDialogClose">取 消</el-button>
          <el-button type="primary" @click="submitUpdateUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 设置用户角色对话框 -->
      <el-dialog title="角色分配" :visible.sync="dialogRoleVisible" width="30%" :before-close="handleRoleClose">
        <el-checkbox v-for="role in roles" v-model="role.checked">{{ role.title }}</el-checkbox>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeUserRole()">取 消</el-button>
          <el-button type="primary" @click="changeUserRole()">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import QueryOptions from '@/components/QueryOptions.vue'
export default {
  data() {
    return {
      // 添加用户对话框
      dialogVisible: false,
      // 修改用户对话框
      dialogUpdateVisible: false,
      // 修改用户角色对话框
      dialogRoleVisible: false,
      // role,user修改对象
      roleUserOpt: {
        userId: null,
        roleIds: []
      },
      // 角色列表
      roles: [],
      // 对其方式
      align: "center",
      // 用户数据
      userList: [],
      // 请求
      queryBody: {
        page: 1,
        pageSize: 5,
        status: null,
        nickname: null,
        username: null,
        dept: null
      },
      // 用户总数
      userTotal: 0,
      // 添加用户载体
      userForm: {},
      userFormBak: {
        createDate: null,
        deptId: 0,
        deptName: "总公司",
        email: "",
        id: 0,
        nickname: "",
        password: "",
        checkPass: "",
        picture: "",
        remark: "这人很懒，暂无备注",
        sex: 1,
        status: 1,
        username: ""
      },
      // 部门树型props
      deptProps: {
        label: "title",
        children: "children"
      },
      // 部门树
      deptTree: [],
      // dept名
      deptName: "选择部门",
      // 下拉搜索
      status: [
        {
          value: '1',
          label: '正常'
        },
        {
          value: '2',
          label: '冻结'
        }
      ],
      selectedUsers: [],
      operates: [
        {
          value: '1',
          label: '启用'
        },
        {
          value: '2',
          label: '冻结'
        },
        {
          value: '3',
          label: '删除'
        }
      ],
      operation: ''
    }
  },
  methods: {
    search() {
      console.log("搜索");
      this.getUserList();
    },
    async activeUser(row) {
      const { data: result } = await this.$http.put("/user/active", { id: row.id });
      if (result.success) {
        this.$message.success(result.data);
        this.search();
      } else {
        this.$message.error(result.errorMsg);
      }

    },
    async freezeUser(row) {
      const { data: result } = await this.$http.put("/user/freeze", { id: row.id });
      if (result.success) {
        this.$message.success(result.data);
        this.search();
      } else {
        this.$message.error(result.errorMsg);
      }

    },
    async deleteUser(row) {
      const { data: result } = await this.$http.delete("/user", { params: { id: row.id } });
      if (result.success) {
        this.$message.success(result.data);
        this.search();
      } else {
        this.$message.error(result.errorMsg);
      }

    },
    async updateUser(row) {
      // 0.获取用户数据
      console.log("update user", row);
      const { data: result } = await this.$http.get("/user/" + row.id);
      if (result.success) {
        this.userForm = row;
        // 1.打开用户修改弹窗
        this.dialogUpdateVisible = true;
      } else {
        this.$message.error(result.errorMsg);
      }
      // 2.修改
    },
    // 关闭修改用户信息对话框
    updateDialogClose() {
      this.userForm = this.userFormBak;
      this.dialogUpdateVisible = false;
    },
    // 提交修改的用户信息并
    async submitUpdateUser() {
      const { data: result } = await this.$http.post("/user", this.userForm);
      if (result.success) {
        this.$message.success("修改信息成功");
        this.updateDialogClose();
      } else {
        this.$message.error(result.errorMsg);
      }
    },
    async submitAddUser() {
      const { data: result } = await this.$http.post("/user", this.userForm);
      if (result.success) {
        this.$message.success(result.data);
        this.userForm = this.userFormBak;
        this.dialogVisible = false;
      } else {
        this.$message.error(result.errorMsg);
      }

    },
    async rest_pwd() {
      let ids = new Array();
      this.selectedUsers.forEach(item => {
        ids.push(item.id);
      })
      console.log("ids", ids);
      if (ids.length == 0) {
        return this.$message.error("选项不能为空")
      }
      const { data: result } = await this.$http.get("/user/resetPassword/" + ids);
      if (result.success) {
        this.$message.success("重置密码成功！");
        this.$refs.multipleTable.clearSelection();
      } else {
        this.$message.error(result.errorMsg);
      }
    },
    async edit_role() {
      console.log("角色分配")
      // 0.判断选中的用户个数，不为1，报错
      if (this.selectedUsers.length == 0) return this.$message.info("请选择用户");
      if (this.selectedUsers.length != 1) return this.$message.info("只能选择一个用户");
      const user = this.selectedUsers[0];
      // 1.获取所有的角色信息
      const { data: allRoles } = await this.$http.get("/role/getAll")
      allRoles.data.forEach(_role => {
        let r = {};
        r.id = _role.id;
        r.title = _role.title;
        r.name = _role.name;
        r.checked = false;
        this.roles.push(r);
      })

      // 2.获取自己所拥护的角色
      const { data: myRoles } = await this.$http.get("/userRole/" + user.id);
      // 匹配已选则的角色

      myRoles.data.forEach(my => {
        for (let i = 0; i < this.roles.length; i++) {
          if (this.roles[i].id == my.roleId) {
            this.roles[i].checked = true;
          }
        }
      })
      console.log(this.roles);
      // 3.显示角色分配对话框
      console.log("-----");
      this.dialogRoleVisible = true;
    },
    // 关闭角色分配
    closeUserRole() {
      this.roles = [];
      this.dialogRoleVisible = false;
    },
    handleRoleClose() {
      this.closeUserRole();
    },
    // 改变角色分配
    async changeUserRole() {
      let roleIds = [];
      this.roles.forEach(role => {
        if (role.checked) roleIds.push(role.id);
      });
      const { data: result } = await this.$http.put("/userRole/" + this.selectedUsers[0].id + "/" + roleIds);
      if (result.success) {
        this.$message.success(result.data);
        this.roles = [];
        this.dialogRoleVisible = false;
      } else {
        this.$message.error(result.errorMsg);
        this.roles = [];
      }
    },
    addUser() {
      this.dialogVisible = true;
      console.log("添加用户")
    },
    operate() {
      console.log(this.operate)
    },
    handleStatus(status) {
      this.queryBody.status = status;
      this.search();
    },
    handleSelectionChange(selectedUsers) {
      // console.log(selectedUsers);
      this.selectedUsers = selectedUsers;
    },
    handleNodeClick(data) {
      console.log("deptTree-Node", data);
      this.queryBody.dept = data.id;
      this.deptName = data.title;
      this.search();
    },
    handleNodeUserDept(data) {
      this.userForm.deptId = data.id;
      this.userForm.deptName = data.title;
    },
    handleSizeChange(pageSize) {
      this.queryBody.pageSize = pageSize;
      this.search();
    },
    handleCurrentChange(currentPage) {
      this.queryBody.page = currentPage;
      this.search();
    },
    async getUserList() {
      const { data: result } = await this.$http.get("/user/getByPageAndCondition", { params: this.queryBody });
      if (result.success) {
        this.userList = result.data.records;
        this.userTotal = result.data.total;
        console.log(result.data);
      }
    },
    async getDeptTree() {
      const { data: result } = await this.$http.get("/dept/tree");
      console.log(result.data);
      if (result.success) {
        this.deptTree = result.data;
      }
    }
  },
  mounted() {
    this.getUserList();
    this.getDeptTree();
  },
  components: {
    "QueryOptions": QueryOptions
  }
}
</script>

<style >
.el-dropdown-link {
  cursor: pointer;
  color: #333;
}

.my-input {
  display: inline;

  border: none;
  font-size: 0.875rem;
}

.el-icon-arrow-down {
  font-size: 1rem;
}
</style>